﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;
using VietPremier.Models;
using VietPremier.Repository;

namespace VietPremier.Controllers
{
    public class HomeController : Controller
    {
        private int pageSize = 20;

        [HttpPost]
        public JsonResult Set_Background()
        {
            using (dbVietPremierDataContext db = new dbVietPremierDataContext())
            {
                EntityBackground background = db.EntityBackgrounds.FirstOrDefault();
                return Json(background);
            }
        }

        public ActionResult Index()
        {
            using (dbVietPremierDataContext db = new dbVietPremierDataContext())
            {
                GetTravelInformationModel model = new GetTravelInformationModel();

                EntityTravelInfo travelInfo = db.EntityTravelInfos.FirstOrDefault();
                if (travelInfo != null)
                {
                    model.travelInfo.Description = travelInfo.Description;
                    //SEO
                    EntitySEO seo = db.EntitySEOs.FirstOrDefault(o => o.Type == "Home");

                    model.travelInfo.Titletag = seo.Titletag;
                    model.travelInfo.Meta_description = seo.Meta_description;
                    model.travelInfo.Meta_keyword = seo.Meta_keyword;

                    foreach (var travelProduct in db.EntityTravelProductions.Where(o => o.IdTravelInfo == travelInfo.Id).OrderBy(o => o.Position))
                    {
                        model.listTravelProduct.Add(new TravelProduct()
                        {
                            Id = travelProduct.Id,
                            Name = travelProduct.Name,
                            Image = travelProduct.Image,
                            Description = travelProduct.Description
                        });

                    }
                    return View(model);

                }
                return View();
            }
        }


        public ActionResult News_Event()
        {
            using (dbVietPremierDataContext db = new dbVietPremierDataContext())
            {
                var query = from p in db.EntityNewEvents
                            where p.Show == true
                            orderby p.DateCreate descending
                            select new GetNewEventModel 
                            {
                                ID = p.Id,
                                Name = p.Name,
                                Description = p.Description                                
                            };

                List<GetNewEventModel> lstNewEvent = new List<GetNewEventModel>();
                lstNewEvent = query.ToList();

                return PartialView(lstNewEvent);
            }            
        }

        public ActionResult Testimonial()
        {
            using (dbVietPremierDataContext db = new dbVietPremierDataContext())
            {
                var query = from p in db.EntityTestimonials
                            select new GetTestimonial
                            {
                                ID = p.Id,
                                Name = p.Name,
                                Review = p.Review
                            };

                List<GetTestimonial> lstTestimonial = new List<GetTestimonial>();
                lstTestimonial = query.ToList();

                return PartialView(lstTestimonial);
            }
        }

        public ActionResult Menu()
        {
            using (dbVietPremierDataContext db = new dbVietPremierDataContext())
            {
                GetMenuModel model = new GetMenuModel();

                foreach (var menu in db.EntityMenus)
                {
                    model.listMenu.Add(new Menu()
                    {
                        Id = menu.Id,
                        Name = menu.Name,
                        Position = menu.Position
                    });
                }

                foreach (var travelProduct in db.EntityTravelProductions.OrderBy(o => o.Position))
                {
                    model.listTravelProduct.Add(new TravelProduct()
                    {
                        Id = travelProduct.Id,
                        Name = travelProduct.Name
                    });
                }

                foreach (var style in db.EntityStyles.OrderBy(o => o.Position))
                {
                    model.listStyle.Add(new Style()
                    {
                        Id = style.Id,
                        Name = style.Name
                    });
                }

                foreach (var destinationArea in db.EntityDestinationAreas)
                {
                    DestinationArea destinationAreaModel = new DestinationArea();
                    destinationAreaModel.IdArea = destinationArea.Id;
                    destinationAreaModel.AreaName = destinationArea.Name;

                    foreach (var destinationCountry in db.EntityDestinationCountries.Where(o => o.IdDestinationArea == destinationArea.Id).GroupBy(o => o.Name).Select(o => o.First()))
                    {
                        EntityDestinationCountry country = db.EntityDestinationCountries.FirstOrDefault(o => o.Id == destinationCountry.Id);
                        destinationAreaModel.listDestinationCountry.Add(new DestinationCountryModel()
                        {
                            Id = destinationCountry.Id,
                            Name = destinationCountry.Name
                        });

                    }
                    model.listDestinationArea.Add(destinationAreaModel);
                }

                return PartialView(model);
            }
        }

        public ActionResult Spotlight()
        {
            using (dbVietPremierDataContext db = new dbVietPremierDataContext())
            {
                GetTravelProductModel model = new GetTravelProductModel();
                foreach (var travelCity in db.EntityTravelCities.Where(o => o.Hot == true).OrderByDescending(o => o.Position))
                {
                    EntityTravelProduction travelProduct = db.EntityTravelProductions.FirstOrDefault(o => o.Id == travelCity.IdTravelProduction);
                    if (travelCity != null)
                    {
                        model.travelProduct.Id = travelProduct.Id;
                        model.travelProduct.Name = travelProduct.Name;
                    }
                    model.listTravelCity.Add(new TravelCity()
                    {
                        Id = travelCity.Id,
                        Name = travelCity.Name,
                        Time = travelCity.Time,
                        Image = travelCity.Image,
                    });

                }

                return PartialView(model);
            }
        }

        public ActionResult TourSearch(int id, int? page)
        {
            using (dbVietPremierDataContext db = new dbVietPremierDataContext())
            {
                //ViewBag.CountryName = (from p in db.EntityDestinationCountries
                //                       join q in db.EntityDestinationStyles on p.Id equals q.IdDestinationCountry
                //                       where q.Id == id
                //                       select p.Name).FirstOrDefault();
                //var query = from p in db.EntityDestinationStyles
                //            join q in db.EntityDestinations on p.Id equals q.IdDestinationStyle
                //            where p.Id == id
                //            select new DestinationStyle
                //            {
                //                IdDestination = q.Id,
                //                DestinationName = q.Name,
                //                Image = q.Image,
                //                Price = q.Price,
                //                TripCode = q.TripCode,
                //                Time = q.Time,
                //                Duration = q.Duration
                //            };
                //if (query.Count() != 0)
                //{
                //    ViewBag.StyleName = db.EntityDestinationStyles.FirstOrDefault(p => p.Id == id).Name;
                //    List<DestinationStyle> lstStyle = new List<DestinationStyle>();
                //    lstStyle = query.ToList();

                //    if (Request.HttpMethod != "GET")
                //    {
                //        page = 1;
                //    }

                //    int pageSize = 10;
                //    int pageNumber = (page ?? 1);
                //    return View(lstStyle.ToPagedList(pageNumber, pageSize));
                //}
                //else
                    return View("Error");


            }
        }

        public ActionResult News_EventDetail(string title)
        {
            using (dbVietPremierDataContext db = new dbVietPremierDataContext())
            {
                int id = Utilities.GetIdByTitle(title, VietPremierMenu.News, VietPremierDetailList.Detail);

                var query = from p in db.EntityNewEvents
                            where p.Id == id
                            orderby p.DateCreate descending
                            select new GetNewEventModel
                            {
                                ID = p.Id,
                                Body = p.Body,
                                Name = p.Name,
                                Meta_description = p.Meta_description,
                                Meta_keyword = p.Meta_keyword,
                                Titletag = p.Titletag
                            };
                if (query != null)
                {
                    GetNewEventModel NewsEvent = new GetNewEventModel();
                    NewsEvent = query.FirstOrDefault();

                    return View(NewsEvent);
                }
                return View();
            }
        }

        public ActionResult OurClient()
        {
            using (dbVietPremierDataContext db = new dbVietPremierDataContext())
            {
                var query = db.EntityOurClients.OrderBy(p=>p.Position);
                if (query != null)
                    return PartialView(query.ToList());
                else
                    return View("Error");
            }
        }

        #region "Left Menu"
        public ActionResult LeftMenu()
        {
            dbVietPremierDataContext db = new dbVietPremierDataContext();
           
            var query = (from p in db.EntityTravelProductions
                         select p).ToList();
            var query1 = (from p in db.EntityStyles
                         select p).ToList();

            var query2 = (from p in db.EntityTravelCities
                          orderby p.Time
                          select new _Time { Time = p.Time }).Distinct().ToList();
             LeftMenuModel model=new LeftMenuModel()             
            {
                listProduction = query,
                listStyle=query1,
                listTime = query2

            };
            return PartialView(model);


        }
        #endregion

        #region "Chat Online"
        public ActionResult Onlinesupport()
        {
            using (dbVietPremierDataContext db = new dbVietPremierDataContext())
            {
                GetChatOnlineModel model = new GetChatOnlineModel();

                foreach (var chatYahoo in db.EntityChatOnlines.OrderBy(o => o.Position).Take(4))
                {
                    model.listChatOnline.Add(new ChatOnline()
                    {
                        Id = chatYahoo.Id,
                        Name = chatYahoo.Name,
                        Yahoo = chatYahoo.Yahoo,
                        Position = chatYahoo.Position,
                        Sky = chatYahoo.Sky
                    });
                }
                return PartialView(model);
            }
        }


        [HttpPost]
        public string file_get_contents(string fileName)
        {
            string sContents = string.Empty;
            if (fileName.ToLower().IndexOf("http:") > -1)
            { // URL 
                System.Net.WebClient wc = new System.Net.WebClient();
                byte[] response = wc.DownloadData(fileName);
                sContents = System.Text.Encoding.ASCII.GetString(response);
            }
            else
            {
                // Regular Filename 
                System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
                sContents = sr.ReadToEnd();
                sr.Close();
            }
            return sContents;
        }


        public string CheckYahoo(string yahoo)
        {
            string YahooString = "http://opi.yahoo.com/online?u=" + yahoo + "&m=a";
            string StatusCode = file_get_contents(YahooString);
            if (StatusCode.ToLower().Contains("not") == false)
            {
                return "Online";
            }//neu bang true thi dang online, cac ban tu lam tiep
            else
            {
                return "Offline";
            }//tu lam
        }

        public string CheckSky(string sky)
        {
            string SkyString = "http://mystatus.skype.com/" + sky + ".num";
            string StatusCode = file_get_contents(SkyString);
            if (StatusCode == "2")
            {
                return "Online";
            }//neu bang true thi dang online, cac ban tu lam tiep
            else
            {
                return "Offline";
            }//tu lam
        }

        
        #endregion

        public ActionResult Footer()
        {
            using (dbVietPremierDataContext db = new dbVietPremierDataContext())
            {
                EntityFooter footer = db.EntityFooters.FirstOrDefault();
                return PartialView(footer);
            }
        }

        #region "Banner"
        public ActionResult Banner()
        {
            using (dbVietPremierDataContext db = new dbVietPremierDataContext())
            {
                var query = db.EntityBanners.OrderBy(p => p.Position);
                if (query != null)
                    return PartialView(query.ToList());
                else
                    return View("Error"); 
            }
        }
        #endregion

        public ActionResult Search(string title, int page = 1)
        {
            using (dbVietPremierDataContext db = new dbVietPremierDataContext())
            {
                if (title != null && title.Trim().Count() > 0)
                {
                    GetTravelCityModel model = new GetTravelCityModel();

                    foreach (var travelcity in db.EntityTravelCities.Where(o => o.Name.Contains(title)).OrderBy(o => o.Name).Skip((page - 1) * pageSize).Take(pageSize))
                    {
                        //EntityDestinationStyle destinationStyle = db.EntityDestinationStyles.FirstOrDefault(o => o.Id == destination.IdDestinationStyle);
                        //EntityDestinationCountry destinationCountry = db.EntityDestinationCountries.FirstOrDefault(o => o.Id == destinationStyle.IdDestinationCountry);
                        //model.CountryName = destinationCountry.Name;

                        // tra ve View item cua search
                        model.SearchItem = title;

                        model.listTravelCity.Add(new TravelCity()
                        {                            
                            Id = travelcity.Id,
                            IdTravelProduct = travelcity.IdTravelProduction,
                            ProductName = travelcity.EntityTravelProduction.Name,
                            Image = travelcity.Image,
                            Price = travelcity.Price,
                            Name = travelcity.Name,
                            Time = travelcity.Time,
                            Duration = travelcity.Duration,
                            
                        });
                    }

                    if (model.listTravelCity.Count() > 1)
                    {
                        model.PagingInfo = new PagingInfo()
                        {
                            CurrentPage = page,
                            ItemsPerPage = pageSize,
                            TotalItems = db.EntityTravelCities.Where(o => o.Name.Contains(title)).Count()
                        };
                        return View(model);
                    }
                    else
                    {
                        EntityTravelCity travelcity = db.EntityTravelCities.FirstOrDefault(o => o.Name.Contains(title));
                        if (travelcity != null)
                        {
                            return RedirectToAction("City", "TravelInformation", new { title = Utilities.Encode(travelcity.Name), country = Utilities.Encode(travelcity.EntityTravelProduction.Name) });
                        }
                        else
                        {
                            return View();
                        }
                    }

                }
            }
            return View();
        }

        public ActionResult Brochure()
        {
            using (dbVietPremierDataContext db = new dbVietPremierDataContext())
            {
                var query = db.EntityBrouchures.OrderBy(p => p.Id);
                if (query != null)
                    return PartialView(query.ToList());
                else
                    return View("Error");
            }
        }

        public ActionResult FollowUs()
        {
            using (dbVietPremierDataContext db = new dbVietPremierDataContext())
            {
                var query = db.EntitySocialNetWorks.OrderBy(p => p.Id);
                if (query != null)
                    return PartialView(query.ToList());
                else
                    return View("Error");
            }
        }

    }
}
